<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    wrapClassName="custom-modal min-base-modal"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    :width="modalWidth"
  >
    <div v-if="modalType === 'delete'">
      <!-- <img src="../../assets/images/systemManage/red-prompt.png" class="mb-4" /> -->
      <div class="text-content">是否确认删除此条数据?</div>
    </div>
    <div v-else>
      <a-form
        ref="formRef"
        :model="formState"
        name="platform-config"
        v-bind="formItemLayout"
        layout="vertical"
      >
        <a-form-item
          label="上级机构名称"
          name="parentId"
          :required="parentRequired"
        >
          <a-tree-select
            placeholder="请选择上级组织机构"
            allow-clear
            tree-default-expand-all
            :tree-data="newTreeData"
            v-model:value="formState.parentId"
            :field-names="{
              children: 'children',
              label: 'name',
              value: 'id'
            }"
            :disabled="parentDisabled"
          >
            <template #title="{ label }">
              <div :title="label" class="ellipsis-label">
                {{ label }}
              </div>
            </template>
          </a-tree-select>
        </a-form-item>
        <a-form-item label="组织机构名称" name="deptName" required>
          <a-input
            v-model:value.trim="formState.deptName"
            placeholder="请输入组织机构名称"
            maxLength="50"
          />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="formState.remark"
            placeholder="请输入备注"
            maxLength="100"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <a-button
        key="back"
        type="cancel"
        @click="handleCancel"
        class="common-buttom"
        >取消</a-button
      >
      <a-button
        key="submit"
        type="submit"
        :loading="loading"
        @click="handleOk"
        class="common-buttom"
      >
        {{ modalType === 'delete' ? '确认' : '保存' }}
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { addOrg, editOrg, deleteOrg } from '@/api/organization'
import type { OrgParams } from '@/api/model/organization'
import { message } from 'ant-design-vue'
// import { cloneDeep } from 'lodash'

const emit = defineEmits(['isOk'])
const props = defineProps({
  treeData: {
    type: Array,
    default: () => []
  },
  rootId: {
    type: String,
    default: ''
  },
  isDataEmpty: {
    type: Boolean,
    default: false
  }
})

const modalType = ref('add')
const modalWidth = ref('')
const parentDisabled = ref(false)
const parentRequired = ref(true)
const modalTitle = ref('')

const formRef = ref()
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 24 }
}

const formState = reactive<OrgParams>({
  deptId: '',
  parentId: undefined,
  deptName: '',
  remark: ''
})

const loading = ref<boolean>(false)
const visible = ref<boolean>(false)

const newTreeData = ref()
const setTreeData = (res: any[]) => {
  newTreeData.value = res
}

const showModal = (type: string, data?: OrgParams) => {
  modalType.value = type
  modalWidth.value = '26.25rem'
  parentDisabled.value = false
  parentRequired.value = true

  if (type === 'add') {
    modalTitle.value = '添加组织机构'
    formState.deptId = undefined
    formState.parentId = undefined
    formState.deptName = ''
    formState.remark = undefined
    if (props.isDataEmpty) {
      parentRequired.value = false
    }
  } else if (type === 'addChild') {
    parentDisabled.value = true
    modalTitle.value = '添加组织机构'
  } else if (type === 'edit') {
    modalTitle.value = '编辑组织机构'
    // if (data) {
    //   console.log('data.deptId: ', data.deptId, newTreeData.value)

    //   const res = cloneDeep(newTreeData.value)
    //   newTreeData.value = addDisabledToNodeAndDescendants(res, data.deptId)
    // }
  } else if (type === 'delete') {
    modalWidth.value = '23.75rem'
    modalTitle.value = '删除'
  }

  visible.value = true
  formRef.value?.resetFields()
  if (data) {
    formState.deptId = data.deptId
    formState.parentId = data.parentId
    formState.deptName = data.deptName
    formState.remark = data.remark

    // 根机构没有上级机构，不支持修改上级机构
    // eslint-disable-next-line eqeqeq
    if (data.deptId == props.rootId) {
      parentRequired.value = false
      parentDisabled.value = true
      formState.parentId = undefined
    }
  }
}

const handleOk = async () => {
  try {
    if (modalType.value === 'delete') {
      await deleteOrgFun()
      return
    }
    await formRef.value.validateFields()
    if (modalType.value === 'add' || modalType.value === 'addChild') {
      await addOrgFun()
    } else if (modalType.value === 'edit') {
      await editOrgFun()
    }
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}

const handleCancel = () => {
  visible.value = false
  formRef.value?.resetFields()
}

// 新增组织机构
const addOrgFun = async () => {
  loading.value = true
  addOrg({
    deptName: formState.deptName,
    parentId: formState.parentId?.toString().split('#')[0],
    remark: formState.remark
  })
    .then(() => {
      message.success('添加成功')
      emit('isOk')
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
// 编辑组织机构
const editOrgFun = async () => {
  loading.value = true
  editOrg({
    deptId: formState.deptId,
    deptName: formState.deptName,
    parentId: formState.parentId?.toString().split('#')[0],
    remark: formState.remark
  })
    .then(() => {
      message.success('编辑成功')
      emit('isOk')
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
// 删除组织机构
const deleteOrgFun = async () => {
  loading.value = true
  deleteOrg(formState.deptId as string)
    .then(() => {
      message.success('删除成功')
      emit('isOk')
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// function addDisabledToNodeAndDescendants(tree: any[], id: any): any[] {
//   return tree.map((node) => {
//     // eslint-disable-next-line eqeqeq
//     if (node.id == id) {
//       // 如果找到目标节点，创建一个新的节点对象并添加disabled属性
//       return {
//         ...node,
//         disabled: true,
//         children: addDisabledToDescendants(node.children)
//       }
//     } else {
//       // 如果当前节点不是目标节点，递归调用函数继续遍历子孙节点
//       return {
//         ...node,
//         children: addDisabledToNodeAndDescendants(node.children, id)
//       }
//     }
//   })
// }

// function addDisabledToDescendants(children: any[]): any[] {
//   // 递归处理子孙节点
//   return children?.map((child) => ({
//     ...child,
//     disabled: true,
//     children: addDisabledToDescendants(child.children)
//   }))
// }

defineExpose({ showModal, setTreeData })
</script>
